package com.wondream.myframework.heima_concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 卖票的并发分析
 */
public class TicketTest001 {
    static Random random = new Random();

    public static int randomAmount(){
        return random.nextInt(5)+1;
    }

    public static void main(String[] args) throws Exception {
        TicketWindow ticketWindow = new TicketWindow(10);
        AtomicInteger saleNum = new AtomicInteger();
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                int num = 0;
                try {
                    num = ticketWindow.sell(randomAmount());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                saleNum.addAndGet(num);
            });
            thread.start();
            threadList.add(thread);
        }
        for (Thread thread:
                threadList) {
            thread.join();
        }
        //统计卖出的票数和剩余的票数
        System.out.println("剩余的票数:"+ticketWindow.getCount());
        System.out.println("已卖的票数:"+saleNum.get());
    }
}

class TicketWindow {
    private volatile Integer count;

    public TicketWindow(int count){
        this.count = count;
    }

    public int getCount(){
        return this.count;
    }

    public int sell(int amount) throws InterruptedException {
        if(this.count >= amount){
            synchronized(this.count) {
                if(this.count < amount){
                    return 0;
                }
                TimeUnit.SECONDS.sleep(2);
                this.count = this.count - amount;
            }
            return amount;
        } else {
            return 0;
        }
    }
}